﻿using Core.Business.ProjectModule;
using Core.Business.SocketModule;
using Core.Business.UserModule;
using Core.DataAccess.Model.Project.Queue;
using Core.DataAccess.Model.Projects;
using Core.Framework.Model.Common;
using Core.IBusiness.IProjectModule;
using Core.IBusiness.ISocketModule;
using Core.IBusiness.IUserModule;
using Core.Middleware.WebSockets;
using LogDashboard;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.IO;
using Core.DataAccess.Model.ProjectLogs;
using Core.Business.LoggerModule;
using Core.IBusiness.ILoggerModule;

namespace Core.WebSocketApi
{
    public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            CoreStartupHelper.Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            // Log Dashboard
            // services.AddLogDashboard();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Itool Api", Version = "v1" });

                var basePath = AppContext.BaseDirectory;

                var xmlPath = Path.Combine(basePath, "Swagger.xml");

                c.OperationFilter<AssignOperationVendorExtensions>();
                c.OperationFilter<FormDataOperationFilter>();

                c.IncludeXmlComments(xmlPath);
            });

            services
                .AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddJsonOptions(o => o.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss");

            BuildServiceProvider
                .ServiceCollection

                .AddTransient<ProjectContext>()
                .AddTransient<ProjectLogsContext>()
                .AddTransient<ProjectSocketContext>()

                .AddSingleton<ILog, Loggers>()

                .AddSingleton<IProject, Project>()
                .AddSingleton<IProjectUser, ProjectUsers>()

                .AddSingleton<ISocketGroup, SocketGroup>()
                .AddSingleton<ISocketRelationship, SocketRelationship>()
                .AddSingleton<ISocketMessage, SocketMessage>()

                .AddSingleton<ISocketUser,SocketUsers>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {

            lifetime.ApplicationStopped.Register(() =>
            {
                Console.WriteLine("系统退出");
            });

            lifetime.ApplicationStopping.Register(() =>
            {
                Console.WriteLine("系统准备退出...");
                app.UninstallWebSocketServiceClient();
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseSwagger(c =>
            {
                c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Host = httpReq.Host.Value);
            });

            app.UseHSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); });


            BuildServiceProvider
                .ServiceProvider = app.ApplicationServices;

            // 启用Https
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            // WS中间件
            app
                .UseWebSocketsMiddleware()
                .UseQueueLoop()
                .UseQueueUntreatedLoop();
            //.UseLog4net(loggerFactory);

            // 跨域
            app.UseCors(builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

            app.UseMvc();

        }
    }
}
